import AuthAPI, { type LoginData } from "@/api/auth";
import UserAPI, { type UserInfo } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import RoleAPI from "@/api/role";

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roleList: [],
    perms: []
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data: any) => {
          console.log("data", data);

          const { token } = data;
          localStorage.setItem(TOKEN_KEY, token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      UserAPI.getInfo()
        .then((data: any) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }

          data.perms = extractPermissions(data.menuTreeVoList, []);
          if (!data.perms || data.perms.length <= 0) {
            reject("getUserInfo: perms must be a non-null array!");
            return;
          }
          Object.assign(user.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function getEmployeeList(params: any) {
    return UserAPI.list(params)
  }

  function createEmployee(data: any) {
    return UserAPI.create(data)
  }

  function updateEmployee(data: any) {
    return UserAPI.update(data)
  }

  function deleteEmployee(params: any) {
    return UserAPI.del(params)
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          localStorage.setItem(TOKEN_KEY, "");
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      localStorage.setItem(TOKEN_KEY, "");
      resetRouter();
      resolve();
    });
  }

  function getRoleList(data: any) {
    return RoleAPI.list(data)
  }

  function createRole(data: any) {
    return RoleAPI.save(data)
  }

  function getRoleDetail(data: any) {
    return RoleAPI.detail(data)
  }

  function getMenuTree() {
    return RoleAPI.tree()
  }

  function deleteRole(data: any) {
    return RoleAPI.delete(data)
  }

  function getCurrentDistributorInfo() {
    return UserAPI.getCurrentDistributorInfo()
  }

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
    getRoleList,
    createRole,
    getMenuTree,
    deleteRole,
    getRoleDetail,
    getEmployeeList,
    createEmployee,
    updateEmployee,
    getCurrentDistributorInfo,
    deleteEmployee
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}

function extractPermissions(list: any[], permissions: string[]) {
  list.forEach(item => {
    if (item.permission) {
      permissions.push(item.permission);
    }
    if (item.menuChild && item.menuChild.length > 0) {
      permissions = permissions.concat(extractPermissions(item.menuChild, permissions));
    }
  });
  return permissions;
};
